package com.xuanyuan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanyuan.domain.AjaxResult;
import com.xuanyuan.entity.Notice;
import com.xuanyuan.entity.User;
import com.xuanyuan.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;


@Validated
@Controller
@RequestMapping("/api/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @ResponseBody
    @RequestMapping("/page")
    public AjaxResult selectNoticePage(Notice notice, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return AjaxResult.success(new PageInfo<>(noticeService.selectNoticeList(notice)));
    }

    @ResponseBody
    @RequestMapping("/list")
    public AjaxResult selectNoticeList(Notice notice) {
        return AjaxResult.success(noticeService.selectNoticeList(notice));
    }

    @ResponseBody
    @PostMapping("/add")
    public AjaxResult insertNotice(@Validated Notice notice, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        //设置操作人
        notice.setUserId(sessionUser.getId());
//        if (noticeService.selectNoticeByName(notice.getNoticeName()) != null) {
//            return AjaxResult.error("添加失败，该公告已存在，请换个名字！");
//        } else {
        return AjaxResult.toAjax(noticeService.insertNotice(notice));
//        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public AjaxResult updateNotice(@Validated Notice notice, @NotNull(message = "公告id不能为空") Integer id, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        //设置操作人
        notice.setUserId(sessionUser.getId());
        //必须需要id
        notice.setId(id);
        return AjaxResult.toAjax(noticeService.updateNotice(notice));
    }

    @ResponseBody
    @PostMapping("/removes")
    public AjaxResult deleteNoticeByIds(@NotEmpty(message = "公告ids不能为空") String[] ids) {
        return AjaxResult.toAjax(noticeService.deleteNoticeByIds(ids));
    }
}

